/* eslint-disable no-param-reassign */

import React, { PureComponent } from 'react';
import { connect } from 'dva';
import { DownOutlined, UpOutlined } from '@ant-design/icons';
import { Form } from '@ant-design/compatible';
import '@ant-design/compatible/assets/index.css';
import { Row, Col, Card, Select, Button, DatePicker, Input, Divider, Dropdown, Menu } from 'antd';
import router from 'umi/router';
import queryString from 'query-string';
import moment from 'moment';
import Authorized from '@/utils/Authorized';
import styles from '@/utils/utils.less';
import PageHeaderWrapper from '@/components/PageHeaderWrapper';
import StandardTable from '@/components/StandardTable';
import { checkPermissions } from '@/utils/authority';

const FormItem = Form.Item;
const { RangePicker } = DatePicker;
const { Option } = Select;
@connect(({ payapply, loading, publicdata, login }) => ({
  payapply,
  loading: loading.models.payapply,
  publicdata,
  login,
}))
@Form.create()
class Adjust extends PureComponent {
  state = {
    selectedRowKeys: [],
    selectedRows: [],
  };

  tableSearchLayout = {
    labelCol: { md: { span: 7 } },
    wrapperCol: { md: { span: 17 } },
  };

  componentDidMount() {
    const {
      location,
      payapply: {
        pageData: { pagination },
      },
      dispatch,
      login,
    } = this.props;
    const { systemList } = login;

    const { isMenuLink } = queryString.parse(location.search);
    if (isMenuLink) {
      this.resetAndGeLlist(location);
    } else {
      this.getList(pagination.current, pagination.pageSize);
    }
    let userType;
    systemList.forEach(item => {
      if (item.isSelected) {
        userType = item.sysCode;
      }
    });
    const feeType = ['FM_PAY_STATE'];
    if (userType === 1) {
      // 客服
      feeType.push('CS_FM_PAY_TYPE');
    } else if (userType === 4) {
      // 运行
      feeType.push('OS_FM_PAY_TYPE');
    } else {
      feeType.push('JH_FM_PAY_TYPE');
    }
    dispatch({
      type: 'payapply/queryDictItemsByCodes',
      payload: feeType,
    });
  }

  // 查找列表
  getList = (currentPage = 1, pageSize = 10, queryParam, isClear = true) => {
    const { dispatch, form } = this.props;
    if (isClear) {
      this.setState({
        selectedRowKeys: [],
        selectedRows: [],
      });
    }
    form.validateFields(['payee', 'payState', 'creTime', 'feeType'], (err, fieldsValue) => {
      if (err) return;
      fieldsValue = queryParam || fieldsValue;
      dispatch({
        type: 'payapply/updateModelData',
        payload: { formFieldsValue: fieldsValue },
      });
      const formFieldsValue = {};
      Object.keys(fieldsValue).forEach(key => {
        if (key === 'creTime') {
          formFieldsValue.startDate =
            (fieldsValue.creTime &&
              fieldsValue.creTime[0] &&
              fieldsValue.creTime[0].format('YYYY-MM-DD')) ||
            null;
          formFieldsValue.endDate =
            (fieldsValue.creTime &&
              fieldsValue.creTime[1] &&
              fieldsValue.creTime[1].format('YYYY-MM-DD')) ||
            null;
        } else {
          formFieldsValue[key] = fieldsValue[key] === undefined ? null : fieldsValue[key].trim();
        }
        delete formFieldsValue.creTime;
      });
      const pageArg = { currentPage, pageSize };
      dispatch({
        type: 'payapply/fetchList',
        payload: {
          pageArg,
          ...formFieldsValue,
        },
      });
    });
  };

  // 渲染表单
  renderForm = () => {
    const {
      payapply: { expandForm },
    } = this.props;
    return expandForm ? this.renderAdvancedForm() : this.renderSimpleForm();
  };

  // 重置
  resetSearch = () => {
    const { form, dispatch } = this.props;
    form.resetFields();
    dispatch({
      type: 'payapply/updateModelData',
      payload: { formFieldsValue: {} },
    });
    form.setFieldsValue({
      creTime: null,
    });
  };

  // 切换展开收起
  toggleForm = () => {
    const {
      payapply: { expandForm },
      dispatch,
    } = this.props;
    dispatch({
      type: 'payapply/updateModelData',
      payload: { expandForm: !expandForm },
    });
  };

  // 支付菜单跳转
  goSubmit = val => {
    router.push(`/fmmanage/payapply/payapplysubmit?payapplytype=${val}`);
  };

  // 展开之后的表单项
  renderAdvancedForm = () => {
    const {
      form: { getFieldDecorator },
      payapply: { payStatusList, formFieldsValue, payPurposeList },
    } = this.props;
    return (
      <Form layout="inline">
        <Row gutter={{ md: 8, lg: 24, xl: 48 }}>
          <Col md={8} sm={24}>
            <FormItem label="收款人" {...this.tableSearchLayout}>
              {getFieldDecorator('payee', {
                initialValue: formFieldsValue.payee,
              })(<Input placeholder="请输入" />)}
            </FormItem>
          </Col>
          <Col md={8} sm={24}>
            <FormItem label="支付状态" {...this.tableSearchLayout}>
              {getFieldDecorator('payState', {
                initialValue: formFieldsValue.payState,
              })(
                <Select
                  placeholder="请选择"
                  style={{ width: '100%' }}
                  allowClear
                  optionFilterProp="children"
                  showSearch
                >
                  {payStatusList.map(item => (
                    <Option key={item.itemCode}>{item.itemName}</Option>
                  ))}
                </Select>
              )}
            </FormItem>
          </Col>
          <Col md={8} sm={24}>
            <FormItem label="支付用途" {...this.tableSearchLayout}>
              {getFieldDecorator('feeType', {
                initialValue: formFieldsValue.feeType,
              })(
                <Select
                  placeholder="请选择"
                  style={{ width: '100%' }}
                  allowClear
                  optionFilterProp="children"
                  showSearch
                >
                  {payPurposeList.map(item => (
                    <Option key={item.itemCode}>{item.itemName}</Option>
                  ))}
                </Select>
              )}
            </FormItem>
          </Col>
        </Row>
        <Row gutter={{ md: 8, lg: 24, xl: 48 }}>
          <Col md={8} sm={24}>
            <FormItem label="申请时间" {...this.tableSearchLayout}>
              {getFieldDecorator('creTime', {
                initialValue: formFieldsValue.creTime,
              })(<RangePicker style={{ width: '100%' }} />)}
            </FormItem>
          </Col>
          <Col md={8} sm={24} offset={8}>
            <div style={{ overflow: 'hidden' }}>
              <div style={{ float: 'right', marginBottom: 24 }}>
                <Button type="primary" htmlType="submit" onClick={() => this.getList()}>
                  查询
                </Button>
                <Button style={{ marginLeft: 8 }} onClick={this.resetSearch}>
                  重置
                </Button>
                <a style={{ marginLeft: 8 }} onClick={this.toggleForm}>
                  收起 <UpOutlined />
                </a>
              </div>
            </div>
          </Col>
        </Row>
      </Form>
    );
  };

  // 展开之前的表单项
  renderSimpleForm = () => {
    const {
      form: { getFieldDecorator },
      payapply: { formFieldsValue, payStatusList },
    } = this.props;
    return (
      <Form layout="inline">
        <Row gutter={{ md: 8, lg: 24, xl: 48 }}>
          <Col md={8} sm={24}>
            <FormItem label="收款人" {...this.tableSearchLayout}>
              {getFieldDecorator('payee', {
                initialValue: formFieldsValue.payee,
              })(<Input placeholder="请输入" />)}
            </FormItem>
          </Col>
          <Col md={8} sm={24}>
            <FormItem label="支付状态" {...this.tableSearchLayout}>
              {getFieldDecorator('payState', {
                initialValue: formFieldsValue.payState,
              })(
                <Select
                  placeholder="请选择"
                  style={{ width: '100%' }}
                  allowClear
                  optionFilterProp="children"
                  showSearch
                >
                  {payStatusList.map(item => (
                    <Option key={item.itemCode}>{item.itemName}</Option>
                  ))}
                </Select>
              )}
            </FormItem>
          </Col>
          <Col md={8} sm={24}>
            <span className={styles.submitButtons}>
              <Button type="primary" htmlType="submit" onClick={() => this.getList()}>
                查询
              </Button>
              <Button style={{ marginLeft: 8 }} onClick={this.resetSearch}>
                重置
              </Button>
              <a style={{ marginLeft: 8 }} onClick={this.toggleForm}>
                展开 <DownOutlined />
              </a>
            </span>
          </Col>
        </Row>
      </Form>
    );
  };

  // 选中表格中一行时候
  handleSelectRows = (selectedRows, selectedKeys) => {
    this.setState({ selectedRows, selectedRowKeys: selectedKeys });
  };

  handleStandardTableChange = pagination => {
    this.getList(pagination.current, pagination.pageSize, undefined, false);
  };

  // 重置查询条件并获取列表
  async resetAndGeLlist(location) {
    const { dispatch } = this.props;
    const { queryParam } = location;
    await this.resetSearch();
    await this.getList(undefined, undefined, queryParam);
    dispatch({
      type: 'payapply/updateModelData',
      payload: { expandForm: Boolean(queryParam) },
    });
    dispatch({
      type: 'global/changeIsMenuLink',
      payload: location,
    });
  }

  render() {
    const {
      payapply: { pageData },
      loading,
    } = this.props;
    const { selectedRowKeys, selectedRows } = this.state;

    const columns = [
      {
        title: '收款人',
        dataIndex: 'payee',
        onHeaderCell: () => ({ style: { fontWeight: 'bold' } }),
      },
      {
        title: '支付用途',
        dataIndex: 'feeTypeName',
        onCell: () => ({
          style: {
            textAlign: 'center',
          },
        }),
        onHeaderCell: () => ({
          style: {
            textAlign: 'center',
            fontWeight: 'bold',
          },
        }),
      },
      {
        title: '支出金额(元)',
        dataIndex: 'actualAmount',
        onHeaderCell: () => ({ style: { fontWeight: 'bold', textAlign: 'right' } }),
        onCell: () => ({
          style: {
            textAlign: 'right',
          },
        }),
      },
      {
        title: '申请人',
        dataIndex: 'aplctName',
        onHeaderCell: () => ({ style: { fontWeight: 'bold' } }),
      },
      {
        title: '支付状态',
        dataIndex: 'payStateName',
        onHeaderCell: () => ({ style: { fontWeight: 'bold' } }),
      },
      {
        title: '申请时间',
        dataIndex: 'applTime',
        onCell: () => ({
          style: {
            textAlign: 'center',
          },
        }),
        onHeaderCell: () => ({
          style: {
            textAlign: 'center',
            fontWeight: 'bold',
          },
        }),
        render: text => text && moment(text).format('YYYY-MM-DD HH:mm'),
      },
      {
        title: '操作',
        onHeaderCell: () => ({ style: { fontWeight: 'bold', width: 140, textAlign: 'center' } }),
        onCell: () => ({
          style: {
            textAlign: 'center',
          },
        }),
        render: (text, record) => (
          <span>
            <span
              style={{ color: '#1890FF', cursor: 'pointer' }}
              onClick={() => {
                router.push(
                  `/fmmanage/payapply/detail?paymentId=${record.paymentId}&payState=${
                    record.payState
                  }  `
                );
              }}
            >
              查看
            </span>
            {+record.payState === 1 && (
              <Authorized authority="business:pay:cancelApply">
                <Divider type="vertical" />
                <span
                  style={{ color: '#1890FF', cursor: 'pointer' }}
                  onClick={() =>
                    router.push(`/fmmanage/payapply/canclefmpay?paymentId=${record.paymentId}`)
                  }
                >
                  取消申请
                </span>
              </Authorized>
            )}
          </span>
        ),
      },
    ];
    const payMenu = (
      <Menu>
        {checkPermissions('business:pay:refund') && (
          <Menu.Item onClick={() => this.goSubmit(1)}>返款支付</Menu.Item>
        )}
        {checkPermissions('business:pay:cust') && (
          <Menu.Item onClick={() => this.goSubmit(2)}>客户费用退费</Menu.Item>
        )}
        {checkPermissions('business:pay:recvRefund') && (
          <Menu.Item onClick={() => this.goSubmit(3)}>返款支付</Menu.Item>
        )}
        {checkPermissions('business:pay:sendSupp') && (
          <Menu.Item onClick={() => this.goSubmit(4)}>付款账单支付</Menu.Item>
        )}
        {checkPermissions('business:pay:insBill') && (
          <Menu.Item onClick={() => this.goSubmit(5)}>社保账单支付</Menu.Item>
        )}
        {checkPermissions('business:pay:accuBill') && (
          <Menu.Item onClick={() => this.goSubmit(6)}>公积金账单支付</Menu.Item>
        )}
      </Menu>
    );
    return (
      <PageHeaderWrapper>
        <Card className={styles.searchCard}>
          <div className={styles.tableListForm}>{this.renderForm()}</div>
        </Card>
        {this.selectedRowKeys}
        <Card className={styles.tabCard}>
          <div className={styles.tableList}>
            <div>
              <Row style={{ margin: '12px 0px 16px' }}>
                <Dropdown overlay={payMenu}>
                  <Button type="primary">
                    支付申请 <DownOutlined />
                  </Button>
                </Dropdown>
              </Row>
              <StandardTable
                selectedRows={selectedRows}
                loading={loading}
                selectedRowKeys={selectedRowKeys}
                data={pageData}
                columns={columns}
                rowKey="paymentId"
                onSelectRow={this.handleSelectRows}
                onChange={this.handleStandardTableChange}
              />
            </div>
          </div>
        </Card>
      </PageHeaderWrapper>
    );
  }
}

export default Adjust;
